package org.crl.blogsystem.service;

import jakarta.transaction.Transactional;
import org.crl.blogsystem.entity.Blog;
import org.crl.blogsystem.entity.Like;
import org.crl.blogsystem.entity.User;
import org.crl.blogsystem.entity.dto.LikeDTO;
import org.crl.blogsystem.repository.BlogRepository;
import org.crl.blogsystem.repository.LikeRepository;
import org.crl.blogsystem.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service

public class LikeService implements ILikeService{
    @Autowired
    LikeRepository likeRepository;

    @Autowired
    BlogRepository blogRepository;

    @Autowired
    UserRepository usersRepository;

    @Override
    public void like(Long blogId, Long userId) {
        Blog blog = blogRepository.findById(blogId).orElse(null);
        User user = usersRepository.findById(userId).orElse(null);
        Like like = new Like();
        like.setBlog(blog);
        like.setUser(user);
        likeRepository.save(like);
        if (blog != null) {
            blog.setLikesCount(blog.getLikesCount() + 1);
            blogRepository.save(blog);
        }
    }

    @Override
    @Transactional
    public void deleteByUserIdAndBlogId(Long userId, Long blogId) {
        likeRepository.deleteByUserIdAndBlogId(userId, blogId);
        Blog blog = blogRepository.findById(blogId).orElse(null);
        if (blog != null) {
            blog.setLikesCount(blog.getLikesCount() - 1);
            blogRepository.save(blog);
        }
    }

    @Override
    public boolean existsByUser_IdAndBlog_Id(Long userId, Long blogId) {
        return likeRepository.existsByUser_IdAndBlog_Id(userId, blogId);
    }
}
